package com.wwwarehouse.carddesk.fragment.mytabfragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.Base64Utils;
import com.wwwarehouse.common.tools.rsa.RSAUtil;
import com.wwwarehouse.common.tools.rsa.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * author ：minifly
 * date: 2017/10/21
 * time: 10:52
 * desc: 信息页面修改用户名与邮箱页面
 */
public class MyMessageChangePasswordFragment extends BaseFragment{

    private View v;
    private TextView mDeskMyPasswordUsernametxt;
    private ClearEditText mDeskMyOldpasswordEdittext;
    private ClearEditText mDeskMyNewpasswordEdittext;
    private ClearEditText mDeskMyOldpasswordAgainEdittext;
    private StateButton mDeskMyPasswordBtn;
    private TextInputLayout mDeskMyOldpasswordEdittextLayout;
    private TextInputLayout mDeskMyNewpasswordEdittextLayout;
    private TextInputLayout mDeskMyOldpasswordAgainEdittextLayout;
    private String newPassword;
    private String newPasswordAgain;
    private String oldPassword;
    private View blankView;
    private LinearLayout allLin;
    private static final int REQUEST_DATA_INT = 1001;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_desk_my_message_changepassword, container, false);
        initView(v);
        return v;

    }

    /**
     * 基础判断：
     * 三个输入框遵循注册时提供的密码格式
     * 1.原密码输入完成并失去焦点时需要判断，与该用户设定的原密码是否一致，若不一致则进入错误提示：“原密码不正确”，
     * 2.新密码若格式不正确，进入错误提示，遵循注册时的密码错误提示
     * 3.重复密码若格式不正确，进入错误提示，遵循注册时的密码错误提示
     * 4.当新密码和重复密码已填写值，且都失去焦点时，需要判断两者的是否一致，若不一致，则进入错误提示，“两次输入的密码不一致”，两个输入框均进行错误提示
     * 5.格式输入不正确，优先于“两次输入的密码不一致的提示”
     * 6、注册时的密码格式：必须在6-16位之间；必须同时包含数字和字母。不符合6-16位时，提醒“密码须在6-16位之间”；不符合数字字母时，提醒“密码须同时含数字和字母”
     * 7、原密码和新密码不能相同，如果相同需要提示“新密码不能与原密码相同”
     * <p>
     * 当原密码，新密码两次，这三个输入框都输入时，确认修改的按钮才可以点亮，否则处于置灰，禁用状态
     * 流程节点：图2：查看或修改个人信息-2.3
     *
     * @param view
     */

    public void initView(View view) {

        mDeskMyPasswordUsernametxt = (TextView) v.findViewById(R.id.desk_my_password_usernametxt);
        mDeskMyOldpasswordEdittext = (ClearEditText) v.findViewById(R.id.desk_my_oldpassword_edittext);
        mDeskMyNewpasswordEdittext = (ClearEditText) v.findViewById(R.id.desk_my_newpassword_edittext);
        mDeskMyOldpasswordAgainEdittext = (ClearEditText) v.findViewById(R.id.desk_my_oldpassword_again_edittext);

        mDeskMyOldpasswordEdittextLayout = (TextInputLayout) v.findViewById(R.id.desk_my_oldpassword_edittext_layout);
        mDeskMyNewpasswordEdittextLayout = (TextInputLayout) v.findViewById(R.id.desk_my_newpassword_edittext_layout);
        mDeskMyOldpasswordAgainEdittextLayout = (TextInputLayout) v.findViewById(R.id.desk_my_oldpassword_again_edittext_layout);
        blankView = v.findViewById(R.id.desk_my_password_view);
        allLin = (LinearLayout) v.findViewById(R.id.desk_my_password_alllin);

        mDeskMyPasswordUsernametxt.setText("" + getString(R.string.taskdesk_my_message_name_pre) + getArguments().getString("name"));
        mDeskMyPasswordBtn = (StateButton) v.findViewById(R.id.desk_my_password_btn);


        mDeskMyOldpasswordEdittext.setOnMyFocusChangeListener(new ClearEditText.onMyFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                oldJudge();
            }
        });
        mDeskMyOldpasswordEdittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                oldJudge();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mDeskMyNewpasswordEdittext.setOnMyFocusChangeListener(new ClearEditText.onMyFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                newJudge();
            }
        });
        mDeskMyNewpasswordEdittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                newJudge();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mDeskMyOldpasswordAgainEdittext.setOnMyFocusChangeListener(new ClearEditText.onMyFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                newAgainJudge();
            }
        });

        mDeskMyOldpasswordAgainEdittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                newAgainJudge();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



        mDeskMyPasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updatePassword();
            }
        });

        allLin.setFocusableInTouchMode(true);
//        mDeskMyNewpasswordEdittextLayout.setFocusableInTouchMode(true);
//        mDeskMyOldpasswordAgainEdittextLayout.setFocusableInTouchMode(true);

        ((BaseActivity) mActivity).hideSoftByEditViewIds(new int[]{
                R.id.desk_my_oldpassword_edittext,
                R.id.desk_my_newpassword_edittext,
                R.id.desk_my_oldpassword_again_edittext
        });

    }

    public void updatePassword() {
        //URL_MY_PASSWORD_UPDATE
        /**
         * newPwd	新密码	string
         oldPwd	原密码	string
         userId	登录用户id	number
         */
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("oldPwd", encrypt(oldPassword));
        map.put("newPwd",encrypt(newPassword));
        NoHttpUtils.httpPost(CardDeskConstant.URL_MY_PASSWORD_UPDATE,map,myResponseListener,REQUEST_DATA_INT);
        LogUtils.showErrLog("更新密码操作。" + map.toString());
    }

    NoHttpUtils.OnResponseListener myResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            if("0".equals(commonClass.getCode())){
//                LogUtils.showErrLog("改动密码返回：  " + commonClass.getData().toString());

                ToastUtils.showToastAtTop("" + getString(R.string.taskdesk_my_message_password_change_success) );
                mDeskMyOldpasswordEdittext.setText("");
                mDeskMyNewpasswordEdittext.setText("");
                mDeskMyOldpasswordAgainEdittext.setText("");
                switch (i){
                    case REQUEST_DATA_INT:

                        break;
                }
                popFragment();

            }else{
                ToastUtils.showToastAtTop("" + commonClass.getMsg());
            }

        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };



    @Override
    public void setTitle() {
        if (peekFragment() instanceof MyMessageChangePasswordFragment) {
            mActivity.setTitle(getString(R.string.taskdesk_my_changepassword));
        }
    }

    @Override
    public void requestDatas() {

    }


    //密码6-16位，由字母加数字组成
    private static final String REGEX = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";

    public boolean judgePasswordLedge(String destStr) {
        return destStr.matches(REGEX);
    }

    public void judgeConfirmBtn() {
        if(!StringUtils.isNullString(newPasswordAgain) && !StringUtils.isNullString(newPassword) && !StringUtils.isNullString(oldPassword)){
            if(newPasswordAgain.equals(newPassword)){
                mDeskMyOldpasswordAgainEdittextLayout.setStateNormal();
                mDeskMyNewpasswordEdittextLayout.setStateNormal();
                if(judgePasswordLedge(newPasswordAgain) && judgePasswordLedge(newPassword) && judgePasswordLedge(oldPassword)){
                    mDeskMyPasswordBtn.setText(getString(R.string.button_text_save));
                    mDeskMyPasswordBtn.setEnabled(true);
                }
            }else{
                if (judgePasswordLedge(newPasswordAgain)) {
                    mDeskMyOldpasswordAgainEdittextLayout.setStateWrong("" + getString(R.string.taskdesk_my_message_password_twice_error));
                }
                if(judgePasswordLedge(newPassword)){
                    mDeskMyNewpasswordEdittextLayout.setStateWrong("" + getString(R.string.taskdesk_my_message_password_twice_error));
                }
                mDeskMyPasswordBtn.setText(getString(R.string.confirm));
                mDeskMyPasswordBtn.setEnabled(false);
            }
        }else{
            if(!StringUtils.isNullString(newPasswordAgain) && !StringUtils.isNullString(newPassword)){
                if(newPasswordAgain.equals(newPassword)){
                    mDeskMyOldpasswordAgainEdittextLayout.setStateNormal();
                    mDeskMyNewpasswordEdittextLayout.setStateNormal();
                }else {
                    if (judgePasswordLedge(newPasswordAgain)) {
                        mDeskMyOldpasswordAgainEdittextLayout.setStateWrong("" + getString(R.string.taskdesk_my_message_password_twice_error));
                    }
                    if(judgePasswordLedge(newPassword)){
                        mDeskMyNewpasswordEdittextLayout.setStateWrong("" + getString(R.string.taskdesk_my_message_password_twice_error));
                    }
                }
            }
            mDeskMyPasswordBtn.setText(getString(R.string.confirm));
            mDeskMyPasswordBtn.setEnabled(false);
        }

    }

    public void oldJudge(){
        oldPassword = mDeskMyOldpasswordEdittext.getText().toString().trim();
        if(StringUtils.isNullString(oldPassword)){
            mDeskMyOldpasswordEdittextLayout.setStateNormal();
        }else{
            if (judgePasswordLedge(oldPassword)) {
                mDeskMyOldpasswordEdittextLayout.setStateNormal();
            } else {
                mDeskMyOldpasswordEdittextLayout.setStateWrong(getString(R.string.input_password));
            }
        }

        judgeConfirmBtn();
    }

    public void newJudge(){
        //2.新密码若格式不正确，进入错误提示，遵循注册时的密码错误提示
        //3.重复密码若格式不正确，进入错误提示，遵循注册时的密码错误提示
        //4 当新密码和重复密码已填写值，且都失去焦点时，需要判断两者的是否一致，若不一致，则进入错误提示，“两次输入的密码不一致”，两个输入框均进行错误提示
        //5. 格式输入不正确，优先于“两次输入的密码不一致的提示”
        newPassword = mDeskMyNewpasswordEdittext.getText().toString().trim();

        judgeConfirmBtn();

        if(StringUtils.isNullString(newPassword)){

            mDeskMyNewpasswordEdittextLayout.setStateNormal();
        }else{
            if (judgePasswordLedge(newPassword)) {
                mDeskMyNewpasswordEdittextLayout.setStateNormal();
            } else {
                mDeskMyNewpasswordEdittextLayout.setStateWrong(getString(R.string.input_password));
            }
        }
    }

    public void newAgainJudge(){
        newPasswordAgain = mDeskMyOldpasswordAgainEdittext.getText().toString().trim();

        judgeConfirmBtn();

        if(StringUtils.isNullString(newPasswordAgain)){
            mDeskMyOldpasswordAgainEdittextLayout.setStateNormal();
        }else{
            if (judgePasswordLedge(newPasswordAgain)) {
                mDeskMyOldpasswordAgainEdittextLayout.setStateNormal();
            } else {
                mDeskMyOldpasswordAgainEdittextLayout.setStateWrong(getString(R.string.input_password));
            }
        }
    }

    public String encrypt(String key){
        String result = "";
        try {
            byte[] data = RSAUtil.encryptByPublicKey(key.getBytes(), RSAUtil.publicKey);
            result = Base64Utils.encodeBase64(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
